/*
 *  Copyright (C) 2025 ameise <ameise.wang@gmail.com> - All Rights Reserved
 *
 *  This file is part of e3net.
 *
 *  e3net is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  e3net is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with e3net. If not, see <https://www.gnu.org/licenses/>.
 */

package common

import (
	"runtime"
	"sync/atomic"
)

const (
	stopped int32 = iota
	starting
	started
	stopping
)

type Service struct {
	state int32
}

func (ts *Service) Start(f func() error) (err error) {
	for {
		if atomic.LoadInt32(&ts.state) == started {
			break
		}
		if atomic.CompareAndSwapInt32(&ts.state, stopped, starting) {
			if f != nil {
				if err = f(); err != nil {
					atomic.StoreInt32(&ts.state, stopped)
					return
				}
			}
			atomic.StoreInt32(&ts.state, started)
			break
		}
		runtime.Gosched()
	}
	return
}

func (ts *Service) Stop(f func()) {
	for {
		if atomic.LoadInt32(&ts.state) == stopped {
			break
		}
		if atomic.CompareAndSwapInt32(&ts.state, started, stopping) {
			if f != nil {
				f()
			}
			atomic.StoreInt32(&ts.state, stopped)
			break
		}
		runtime.Gosched()
	}
}

func (ts *Service) IsRunning() bool {
	return atomic.LoadInt32(&ts.state) == started
}

func (ts *Service) IsStopped() bool {
	return atomic.LoadInt32(&ts.state) == stopped
}
